//
//  HDVerifyPhoneNumberView.m
//  HDecoration
//
//  Created by 曹群 on 15/8/15.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//

#import "HDVerifyPhoneNumberView.h"
#import "HDWebViewController.h"
@interface HDVerifyPhoneNumberView ()
@property CGPoint activePoint;
@property(nonatomic,strong)UIImageView *backgroundImage;
@property(nonatomic,strong)UIView *inputView;
@property(nonatomic,strong)HDTextField *phoneNumberField;
@property(nonatomic,strong)HDTextField *verifyCodeField;
@property(nonatomic,strong)HDTextField *passwordField;
@property(nonatomic,strong)HDTextField *confirmPasswordField;
@property(nonatomic,strong)GXButton *acceptBtn;
@property(nonatomic,strong)UIButton *readBtn;
@property(nonatomic,strong)UIButton *nextStepBtn;
@property(nonatomic,strong)UIButton *verifyBtn;
@property NSTimer* time;
@end

@implementation HDVerifyPhoneNumberView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.backgroundImage];
        [self.backgroundImage addSubview:self.inputView];
        [self.backgroundImage addSubview:self.acceptBtn];
        [self.backgroundImage addSubview:self.readBtn];
        [self.backgroundImage addSubview:self.nextStepBtn];
        self.contentSize = CGSizeMake(self.width, self.backgroundImage.height+10);
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [self addGestureRecognizer:tapGesture];
        [self registerForKeyboardNotifications];
    }
    return self;
}

- (void)checkInputFinished
{
    self.nextStepBtn.enabled = (self.phoneNumberField.text.length&&self.verifyCodeField.text.length&&self.passwordField.text.length&&self.confirmPasswordField.text.length&&self.acceptBtn.selected);
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(textBeginEditing:)
                                                name:UITextViewTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(textBeginEditing:)
                                                name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(checkInputFinished)
                                                name:UITextFieldTextDidChangeNotification object:nil];
    
}

- (void)textBeginEditing:(NSNotification*)aNotification
{
    UIView* sender=[aNotification object];
    CGRect rect=sender.frame;
    rect.origin.y+=rect.size.height;
    self.activePoint=[[sender superview] convertPoint:rect.origin toView:self];
    self.activePoint=[self convertPoint:self.activePoint toView:self];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    kbSize.height+=30;
    
    float hiddenH=self.frame.size.height-(self.frame.size.height-kbSize.height);
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0,hiddenH, 0.0);
    self.contentInset = contentInsets;
    self.scrollIndicatorInsets = contentInsets;
    float activeH=self.frame.size.height-self.activePoint.y;
    if(kbSize.height>activeH)
    {
        float dif=activeH-kbSize.height;
        CGPoint scrollPoint = CGPointMake(0.0,0-dif);
        [self setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [UIView animateWithDuration:0.3 animations:^{
        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.contentInset = contentInsets;
        self.scrollIndicatorInsets = contentInsets;
    }];
}

#pragma mark - actions
- (void)tapAction
{
    [self.superview endEditing:YES];
}

- (void)acceptAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    [self checkInputFinished];
}

- (void)readAction:(UIButton *)sender
{
    HDWebViewController *readWebVC = [[HDWebViewController alloc] init];
    readWebVC.titleStr = @"快马学车协议";
    readWebVC.urlStr = [NSString stringWithFormat:@"%@/sktPicture/coach/coach.html",hostUrl];
    [rootNavigation pushViewController:readWebVC animated:YES];
}


- (void)verifyBtnAction:(UIButton *)sender
{
    NSDictionary* params=@{
                           @"mobile_no":self.phoneNumberField.text,
                           @"verify":[NSNumber numberWithInt:2],
                           };
    [netEngine RequestVerifyCodeWithTarget:self hudView:self Data:params];
    
}

-(void)requestVerifyCodeSuccuss
{
    if (self.time)
    {
        [self.time invalidate];
        self.time=nil;
    }
    self.verifyBtn.tag=60;
    self.verifyBtn.enabled=NO;
    self.time=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

-(void)timerAction
{
    self.verifyBtn.tag-=1;
    if (self.verifyBtn.tag<=0)
    {
        self.verifyBtn.enabled=YES;
        [self.verifyBtn setTitle:@"验证" forState:UIControlStateNormal];
    }
    else
    {
        [self.verifyBtn setTitle:[NSString stringWithFormat:@"%zis",self.verifyBtn.tag] forState:UIControlStateNormal];
    }
}

- (void)nextStepAction:(UIButton *)sender
{
    if (![HDUtil checkPassword:self.passwordField.text]) {
        [netEngine showErrorAlertWithMsg:@"密码格式不正确，6-16位的字母、数字或符号的组合"];
        return;
    }
    self.registerInfo.phoneNumber = self.phoneNumberField.text;
    self.registerInfo.password = self.passwordField.text;
    self.registerInfo.verifyCode=netEngine.verifyCode;
    if(![self.registerInfo.verifyCode isEqualToString:self.verifyCodeField.text])
    {
        [HDUtil showTipAlertWithMsg:@"验证码校验错误,请核对后继续。"];
        return;
    }
    if(![self.passwordField.text isEqualToString:self.confirmPasswordField.text])
    {
        [HDUtil showTipAlertWithMsg:@"密码校验错误,请核对后继续。"];
        return;
    }
    if ([self.delegate respondsToSelector:@selector(nextStepAction:)])
    {
        [self.delegate performSelector:@selector(nextStepAction:) withObject:self.registerInfo];
    }
}

#pragma mark - getters
- (UIImageView *)backgroundImage
{
    if (!_backgroundImage) {
        _backgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, APPFRAME.size.width-20, (APPFRAME.size.width-20)*768/600.0)];
        UIImage *image = [UIImage imageNamed:@"系统帮助背景"];
        image = [image stretchableImageWithLeftCapWidth:0 topCapHeight:_backgroundImage.height-10];
        _backgroundImage.image = image;
        _backgroundImage.layer.masksToBounds = YES;
        _backgroundImage.userInteractionEnabled = YES;
    }
    return _backgroundImage;
}

- (UIView *)inputView
{
    if (!_inputView) {
        _inputView = [[UIView alloc] initWithFrame:CGRectMake(10, 20, self.backgroundImage.width-20, 200)];
        _inputView.layer.borderColor = [UIColor colorWithRed:0.8824 green:0.8824 blue:0.8824 alpha:1].CGColor;
        _inputView.layer.borderWidth = 0.5;
        _inputView.layer.cornerRadius = 5;
        for (int i=0; i<3; i++) {
            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(15, (i+1)*50, _inputView.width-30, 0.5)];
            line.image = [UIImage imageNamed:@"dot"];
            [_inputView addSubview:line];
        }
        [_inputView addSubview:self.phoneNumberField];
        [_inputView addSubview:self.verifyCodeField];
        [_inputView addSubview:self.passwordField];
        [_inputView addSubview:self.confirmPasswordField];
    }
    return _inputView;
}

- (HDTextField *)phoneNumberField
{
    if (!_phoneNumberField) {
        _phoneNumberField = [[HDTextField alloc] initWithFrame:CGRectMake(10, 0, self.backgroundImage.width-40, 50)icon:@"号码" title:nil];
        _phoneNumberField.placeholder = @"请输入手机号码";
        _phoneNumberField.font = [UIFont systemFontOfSize:15];
        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 0.5, 34)];
        line.image = [UIImage imageNamed:@"dot"];
        self.verifyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _verifyBtn.frame = CGRectMake(10, 7, 60, 30);
        [_verifyBtn setBackgroundImage:[UIImage imageNamed:@"验证"] forState:UIControlStateNormal];
        [_verifyBtn setTitle:@"验证" forState:UIControlStateNormal];
        [_verifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _verifyBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.verifyBtn addTarget:self action:@selector(verifyBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [rightView addSubview:line];
        [rightView addSubview:_verifyBtn];
        _phoneNumberField.rightViewMode = UITextFieldViewModeAlways;
        _phoneNumberField.rightView = rightView;
    }
    return _phoneNumberField;
}

- (HDTextField *)verifyCodeField
{
    if (!_verifyCodeField) {
        _verifyCodeField = [[HDTextField alloc] initWithFrame:CGRectMake(10, self.phoneNumberField.bottom, self.phoneNumberField.width, 50)icon:@"验证码" title:nil];
        _verifyCodeField.placeholder = @"请输入验证码";
        _verifyCodeField.font = [UIFont systemFontOfSize:15];
    }
    return _verifyCodeField;
}

- (HDTextField *)passwordField
{
    if (!_passwordField) {
        _passwordField = [[HDTextField alloc] initWithFrame:CGRectMake(10, self.verifyCodeField.bottom, self.phoneNumberField.width, 50)icon:@"密码" title:nil];
        _passwordField.placeholder = @"设置您的登录密码";
        _passwordField.secureTextEntry=YES;
        _passwordField.font = [UIFont systemFontOfSize:15];
    }
    return _passwordField;
}

- (HDTextField *)confirmPasswordField
{
    if (!_confirmPasswordField) {
        _confirmPasswordField = [[HDTextField alloc] initWithFrame:CGRectMake(10, self.passwordField.bottom, self.phoneNumberField.width, 50)icon:@"密码" title:nil];
        _confirmPasswordField.secureTextEntry=YES;
        _confirmPasswordField.placeholder = @"确认您的登录密码";
        _confirmPasswordField.font = [UIFont systemFontOfSize:15];
    }
    return _confirmPasswordField;
}

- (GXButton *)acceptBtn
{
    if (!_acceptBtn) {
        _acceptBtn = [GXButton buttonWithType:UIButtonTypeCustom];
        NSString *acceptStr = @"我已经阅读同意";
        CGSize size = [HDUtil getSizeWithText:acceptStr font:[UIFont systemFontOfSize:13]];
        CGSize readTextSize = [HDUtil getSizeWithText:@"《快马学车教练协议》" font:[UIFont systemFontOfSize:13]];
        float width = 32+size.width+readTextSize.width;
        _acceptBtn.frame = CGRectMake((self.backgroundImage.width-width)/2.0, self.inputView.bottom+10, size.width+32, 30);
        _acceptBtn.imageViewFrame = CGRectMake(0, 4, 22, 22);
        _acceptBtn.titleLabelFrame = CGRectMake(32, 0, size.width, 30);
        _acceptBtn.relayout = YES;
        [_acceptBtn setTitle:acceptStr forState:UIControlStateNormal];
        [_acceptBtn setTitleColor:[UIColor hexStringToColor:@"#888888"] forState:UIControlStateNormal];
        _acceptBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_acceptBtn setImage:[UIImage imageNamed:@"同意_未选中"] forState:UIControlStateNormal];
        [_acceptBtn setImage:[UIImage imageNamed:@"同意_选中"] forState:UIControlStateSelected];
        [_acceptBtn addTarget:self action:@selector(acceptAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _acceptBtn;
}

- (UIButton *)readBtn
{
    if (!_readBtn) {
        _readBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *readStr = @"《快马学车教练协议》";
        CGSize size = [HDUtil getSizeWithText:readStr font:[UIFont systemFontOfSize:13]];
        _readBtn.frame = CGRectMake(self.acceptBtn.right, self.acceptBtn.top, size.width, 30);
        [_readBtn setTitle:readStr forState:UIControlStateNormal];
        [_readBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_readBtn setTitleColor:kLightGrayColor forState:UIControlStateHighlighted];
        _readBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_readBtn addTarget:self action:@selector(readAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _readBtn;
}

- (UIButton *)nextStepBtn
{
    if (!_nextStepBtn) {
        _nextStepBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _nextStepBtn.frame = CGRectMake(10, self.acceptBtn.bottom+20, self.backgroundImage.width-20, 44);
        [_nextStepBtn setBackgroundImage:[UIImage imageNamed:@"登录"] forState:UIControlStateNormal];
        [_nextStepBtn setTitle:@"下一步" forState:UIControlStateNormal];
        _nextStepBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_nextStepBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_nextStepBtn addTarget:self action:@selector(nextStepAction:) forControlEvents:UIControlEventTouchUpInside];
        _nextStepBtn.enabled = NO;
    }
    return _nextStepBtn;
}

- (void)dealloc
{
    if (self.time)
    {
        [self.time invalidate];
        self.time=nil;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
